package com.lianyu.wangyiyun.utils;

import android.util.Log;
import android.widget.Toast;

import com.lianyu.wangyiyun.model.Mp3Info;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import cn.leancloud.AVObject;
import cn.leancloud.AVQuery;
import cn.leancloud.AVUser;
import cn.leancloud.types.AVNull;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

import static cn.leancloud.AVOSCloud.getContext;

/**
 * @author Chen Yuguang
 * @date 2021/5/22 4:40
 */
public class CollectManager {

    /**
     * 表名
     */
    public static final String TABLE_NAME = "Music";
    /**
     * 歌曲id
     */
    public static final String COLUMN_NAME_ID = "id";
    /**
     * 歌名
     */
    public static final String COLUMN_NAME_TITLE = "title";
    /**
     * 歌手
     */
    public static final String COLUMN_NAME_ARTIST = "artist";
    /**
     * 歌曲url（路径或网址）
     */
    public static final String COLUMN_NAME_URL = "url";
    /**
     * 专辑url（路径或网址）
     */
    public static final String COLUMN_NAME_ALBUM = "album";
    /**
     * 用户指针
     */
    public static final String COLUMN_NAME_USER = "user";

    private static final String TAG = "CollectManager";

    public interface NextCallback {
        /**
         * 成功后下一步操作
         *
         * @param music 收藏的音乐信息类
         * @author Chen Yuguang
         * @date 2021/5/22 4:55
         */
        void onNext(AVObject music);
    }

    public interface NextCallback2 {
        /**
         * 成功后下一步操作
         *
         * @param mp3Infos 获取的音乐列表
         * @author Chen Yuguang
         * @date 2021/5/22 4:55
         */
        void onNext(List<Mp3Info> mp3Infos);
    }

    public interface NextCallback3 {
        /**
         * 成功后下一步操作
         *
         * @author Chen Yuguang
         * @date 2021/5/22 4:55
         */
        void onNext();
    }

    public interface ErrorCallback {
        /**
         * 失败后下一步操作
         *
         * @param e 错误对象
         * @author Chen Yuguang
         * @date 2021/5/22 4:55
         */
        void onError(Throwable e);
    }

    /**
     * 收藏音乐
     *
     * @param mp3Info      要收藏的音乐信息类
     * @param nextCallback 成功后下一步操作
     * @author Chen Yuguang
     * @date 2021/5/22 4:58
     */
    public static void writeCollect(Mp3Info mp3Info, NextCallback nextCallback) {
        // 构建对象
        AVObject music = new AVObject(TABLE_NAME);

        // 获取当前用户
        AVUser currentUser = AVUser.getCurrentUser();

        if (currentUser == null) {
            Log.e(TAG, "未登录，收藏失败");
            Toast.makeText(getContext(), "未登录，收藏失败", Toast.LENGTH_SHORT).show();
        } else {
            // 为属性赋值
            music.put(COLUMN_NAME_ID, mp3Info.getId());
            music.put(COLUMN_NAME_TITLE, mp3Info.getTitle());
            music.put(COLUMN_NAME_ARTIST, mp3Info.getArtist());
            music.put(COLUMN_NAME_URL, mp3Info.getUrl());
            music.put(COLUMN_NAME_ALBUM, mp3Info.getAlbum());
            music.put(COLUMN_NAME_USER, currentUser);

            // 将对象保存到云端
            music.saveInBackground().subscribe(new Observer<AVObject>() {
                @Override
                public void onSubscribe(@NotNull Disposable disposable) {
                }

                @Override
                public void onNext(@NotNull AVObject music) {
                    // 成功保存之后，执行其他逻辑
                    if (nextCallback != null) {
                        nextCallback.onNext(music);
                    }
                }

                @Override
                public void onError(@NotNull Throwable e) {
                    // 异常处理
                    Log.e(TAG, "收藏错误：" + e.getMessage(), e);
                    Toast.makeText(getContext(), "收藏错误，请检查网络", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onComplete() {
                }
            });
        }
    }

    /**
     * 读取收藏列表
     *
     * @param nextCallback  成功后的下一步操作
     * @param errorCallback 失败后的下一步操作
     * @author Chen Yuguang
     * @date 2021/5/22 19:44
     */
    public static void readCollect(NextCallback2 nextCallback, ErrorCallback errorCallback) {
        // 构建对象
        AVQuery<AVObject> query = new AVQuery<>(TABLE_NAME);

        // 获取当前用户
        AVUser currentUser = AVUser.getCurrentUser();

        if (currentUser == null) {
            Log.e(TAG, "未登录，收藏失败");
            Toast.makeText(getContext(), "未登录，收藏失败", Toast.LENGTH_SHORT).show();
            if (errorCallback != null) {
                errorCallback.onError(null);
            }
        } else {
            // 查询条件
            query.whereEqualTo(COLUMN_NAME_USER, currentUser);

            // 按 createdAt 降序排列
            query.orderByDescending("createdAt");

            query.findInBackground().subscribe(new Observer<List<AVObject>>() {
                @Override
                public void onSubscribe(@NotNull Disposable disposable) {
                }

                @Override
                public void onNext(@NotNull List<AVObject> musics) {
                    // musics 是包含满足条件的 music 对象的列表
                    if (nextCallback != null) {
                        nextCallback.onNext(cloud2local(musics));
                    }
                }

                @Override
                public void onError(@NotNull Throwable e) {
                    // 异常处理
                    Log.e(TAG, "读取收藏错误：" + e.getMessage(), e);
                    Toast.makeText(getContext(), "读取收藏错误，请检查网络", Toast.LENGTH_SHORT).show();
                    if (errorCallback != null) {
                        errorCallback.onError(e);
                    }
                }

                @Override
                public void onComplete() {
                }
            });
        }
    }

    /**
     * 删除收藏
     *
     * @param id           要删除收藏的音乐id
     * @param nextCallback 成功后下一步操作
     * @author Chen Yuguang
     * @date 2021/5/22 6:14
     */
    public static void deleteCollect(long id, NextCallback3 nextCallback) {
        // 构建对象
        AVQuery<AVObject> query = new AVQuery<>(TABLE_NAME);

        //查询条件
        query.whereEqualTo(COLUMN_NAME_ID, id);

        //查询头一个符合条件的对象
        query.getFirstInBackground().subscribe(new Observer<AVObject>() {
            @Override
            public void onSubscribe(@NotNull Disposable disposable) {
            }

            @Override
            public void onNext(@NotNull AVObject music) {
                // 删除满足条件的music 对象
                music.deleteInBackground().subscribe(new Observer<AVNull>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@NonNull AVNull avNull) {
                        if (nextCallback != null) {
                            nextCallback.onNext();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        // 异常处理
                        Log.e(TAG, "删除收藏错误：" + e.getMessage(), e);
                        Toast.makeText(getContext(), "删除收藏错误，请检查网络", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                    }
                });
            }

            @Override
            public void onError(@NotNull Throwable e) {
                // 异常处理
                Log.e(TAG, "删除收藏时读取收藏错误：" + e.getMessage(), e);
                Toast.makeText(getContext(), "删除收藏时读取收藏错误，请检查网络", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 清空收藏
     *
     * @param nextCallback 成功后下一步操作
     * @author Chen Yuguang
     * @date 2021/5/22 6:23
     */
    public static void emptyCollect(NextCallback3 nextCallback) {
        // 构建对象
        AVQuery<AVObject> query = new AVQuery<>(TABLE_NAME);

        // 清空收藏
        query.deleteAllInBackground().subscribe(new Observer<AVNull>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
            }

            @Override
            public void onNext(@NonNull AVNull avNull) {
                if (nextCallback != null) {
                    nextCallback.onNext();
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                // 异常处理
                Log.e(TAG, "清空收藏错误：" + e.getMessage(), e);
                Toast.makeText(getContext(), "清空收藏错误，请检查网络", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 将获取的AVObject列表转换为本地音乐信息
     *
     * @param musics 要转换为本地音乐信息的AVObject列表
     * @return java.util.List<com.lianyu.wangyiyun.model.Mp3Info>
     * @author Chen Yuguang
     * @date 2021/5/22 4:58
     */
    private static List<Mp3Info> cloud2local(List<AVObject> musics) {
        List<Mp3Info> mp3Infos = new ArrayList<>();
        if (musics != null) {
            for (AVObject music : musics) {
                Mp3Info mp3Info = new Mp3Info();
                long id = music.getLong(COLUMN_NAME_ID);
                String title = music.getString(COLUMN_NAME_TITLE);
                String artist = music.getString(COLUMN_NAME_ARTIST);
                String url = music.getString(COLUMN_NAME_URL);
                String album = music.getString(COLUMN_NAME_ALBUM);
                if (id != 0) {
                    mp3Info.setId(id);
                }
                if (title != null) {
                    mp3Info.setTitle(title);
                }
                if (artist != null) {
                    mp3Info.setArtist(artist);
                }
                if (url != null) {
                    mp3Info.setUrl(url);
                }
                if (album != null) {
                    mp3Info.setAlbum(album);
                }
                mp3Infos.add(mp3Info);
            }
        }
        return mp3Infos;
    }

}
